package com.huarun.module.sys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.huarun.common.BaseController;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.*;
import com.huarun.common.util.http.HttpParamers;
import com.huarun.module.sys.bean.ReturnToWorkUser;
import com.huarun.module.sys.service.IReturnToWorkUserService;
import com.huarun.module.visitorApply.service.VisitorApplyService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/***
 *
 * @author dzm
 * @创建时间 2020-03-02 11:50
 * @Description 复工人员信息
 */
@RestController
@RequestMapping(value = "/wx/work")
public class ReturnToWorkUserController extends BaseController {
	public static final SimpleDateFormat LONG_HOUR_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	public static final String REGEX_MOBILE = "^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
	@Resource
	private IReturnToWorkUserService service;//注入service
	@Resource
	private VisitorApplyService visitorApplyService;

	/**
	 * 根据ID获取复工人员信息
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "复工人员信息管理--根据ID获取数据字复工人员信息", httpMethod = "GET", notes = "根据ID获取复工人员信息")
	@RequestMapping(value = "/getReturnToWorkUser", method = RequestMethod.GET)
	public ResponseMessage<ReturnToWorkUser> getReturnToWorkUserInfoById(@RequestParam Integer id) {
		ResponseMessage<ReturnToWorkUser> rm = new ResponseMessage<ReturnToWorkUser>();
		try {
			ReturnToWorkUser returnToWorkUser = service.getById(id);
			rm.setData(returnToWorkUser);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("查询复工人员信息出错!");
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 根据ID获取复工人员信息
	 * @param mobile
	 * @return
	 */
	@ApiOperation(value = "复工人员信息管理--根据表参数获取数据字复工人员信息", httpMethod = "GET", notes = "根据表参数获取复工人员信息")
	@RequestMapping(value = "/getReturnToWorkUserByField", method = RequestMethod.GET)
	public ResponseMessage<ReturnToWorkUser> getReturnToWorkUserByField(HttpServletRequest request,
			@RequestParam String mobile,@RequestParam String floor,@RequestParam String userName
			,@RequestParam String deptName) {
		ResponseMessage<ReturnToWorkUser> rm = new ResponseMessage<>();
		try {
			log.info("println log info");
			String projectId = request.getHeader("projectId");
			if (StringUtils.isBlank(projectId) || StringUtils.isBlank(mobile)) {
				rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.R_PARAM_ERROR.msg);
				return rm;
			}
			String chunsunProjectId = PropertyUtil.getProperty("chunsun_project_id");
			boolean isChunsun = projectId.equals(chunsunProjectId);
			String chunsunHost = PropertyUtil.getProperty("visitor_a_url");
			String signKey = PropertyUtil.getProperty("sign_key");// 约定密钥
//			Map subject;
//			String userName = null;
//			String companyName = null;
//			String gender = "1";
//			if(isChunsun){
//				JSONObject jsonEmployee = new JSONObject();
//				Map map = new HashMap();
//				map.put("time", System.currentTimeMillis());
//				map.put("mobile", mobile);
//				Gson gson = new Gson();
//				String str = gson.toJson(map);
//				str = str + "&key=" + signKey;
//				String token = MD5Util.crypt(str).toUpperCase();
//				jsonEmployee.put("sign", token);
//				jsonEmployee.put("time", System.currentTimeMillis());
//				jsonEmployee.put("mobile", mobile);
//				String url = chunsunHost + PropertyUtil.getProperty("chunsun_employee_url");
//				JSONObject employee = HttpRequestUtils.httpPost(url, jsonEmployee);
//				if(employee != null){
//					System.out.println("==============我的通行证春笋用户返回:" + employee.toJSONString());
//					JSONObject retdataJson = employee.getJSONObject("Retdata");
//					userName = retdataJson.getString("empName");
//					companyName = retdataJson.getString("companyName");
//					gender = "男".equals(retdataJson.getString("sex")) ? "1":"0";
//				}
//			}else {
//				Map parames = new HashMap();
//				parames.put("mobile", mobile);
//				parames.put("projectId", projectId);
//				subject = this.visitorApplyService.getDepartment(parames);
//				if(subject == null || subject.size() == 0){
//					rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "未获得通行权限");
//					return rm;
//				}
//				userName = (String)subject.get("real_name");
//				companyName = (String)subject.get("department");
//				gender = String.valueOf(subject.get("gender"));
//			}

//			map.put("projectId", projectId);
//			map.put("mobile", mobile);
			ReturnToWorkUser returnToWorkUser = new ReturnToWorkUser();
			returnToWorkUser.setUserName(userName);
			returnToWorkUser.setMobile(mobile);
			returnToWorkUser.setWorkFlag("1");
//			returnToWorkUser.setGender("1");
			returnToWorkUser.setCompanyName(deptName);
			returnToWorkUser.setProjectId(projectId);

			if (projectId.equals(PropertyUtil.getProperty("huarun_e_project_id"))) {
				rm.setData(returnToWorkUser);
			}else {
				Map<String, Object> params = new HashMap<>();
				params.put("toComName", deptName);
				params.put("toEmpName", userName);
				params.put("toEmpMobile", mobile);
				Pattern pattern = Pattern.compile("^(\\d+)");
				Matcher matcher = pattern.matcher(floor);
				if(matcher.find()){
					floor = matcher.group();
				}
				floor = !StringUtils.isEmpty(floor) ? floor : "1";
				params.put("toFloor", floor);
				params.put("visitorName", userName);
				params.put("visitorPhone", mobile);
				params.put("visitorCertNo", null);
				params.put("peopleCount", null);
				params.put("visitReason", "");
				params.put("toDept", deptName);
				params.put("visitDate", null);
				//
				String http;
				String getCodeUrl = "/api/Getqrcode";
				String bcdApiHost = getBcdApiHost(projectId);
				params.put("startTime", getReqHourDate(new Date()));
				params.put("endTime", getReqHourDate(DateUtils.addHour(new Date(), 1)));
				if (isChunsun) {
					params.put("time", System.currentTimeMillis());
					// 签名
					String str = JSON.toJSONString(params) + "&key=" + signKey;
					String md5Str = MD5Util.crypt(str).toUpperCase();
					params.put("sign",md5Str);
					System.out.println("========我的通行证：春笋二维码入参====：" + JSONObject.toJSONString(params));
					JSONObject returnJson = HttpRequestUtils.httpPost(chunsunHost+ getCodeUrl, JSON.toJSONString(params));
					http = returnJson != null ? returnJson.toJSONString() : "";
				}else {
					System.out.println("========我的通行证：二维码入参====：" + JSONObject.toJSONString(params));
					http = HttpRequestUtils.http(bcdApiHost + getCodeUrl, params);
				}
				System.out.println("========我的通行证：二维码返回====：" + http);
				if ("0".equals(String.valueOf(JSONObject.parseObject(http).get("errcode")))) {
					JSONObject retdata = JSONObject.parseObject(http).getJSONObject("Retdata");
					if(isChunsun){
						String qrcodeNo = retdata.getString("qrcodeNo");
						System.out.println("========我的通行证：春笋二维码标记====：" + qrcodeNo);
						returnToWorkUser.setQrcode(qrcodeNo);
					}else {
						String qrcode = retdata.getString("qrcodeAddress");
						System.out.println("========我的通行证：BCD二维码地址====：" + qrcode);
						String fileUrl = replaceLanToWan(qrcode, bcdApiHost);
						returnToWorkUser.setQrcode(fileUrl);
					}
					rm.setData(returnToWorkUser);
				} else {
					String retmsg = String.valueOf(JSONObject.parseObject(http).get("errmsg"));
					rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, retmsg);
					System.out.println(retmsg);
				}

				return rm;
			}
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("查询复工人员信息出错!");
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 新增复工人员
	 * @param returnToWorkUser
	 * @return
	 */
	@ApiOperation(value = "新增复工人员", httpMethod = "POST", notes = "新增复工人员")
	@RequestMapping(value = "/createReturnToWorkUser", method = RequestMethod.POST)
	public ResponseMessage<Map<String, String>> createReturnToWorkUserInfo(
			@RequestBody ReturnToWorkUser returnToWorkUser) {
		ResponseMessage<Map<String, String>> rm = new ResponseMessage<Map<String, String>>();
		try {
			int result = service.save(returnToWorkUser);
			log.info("新增{}条复工人员", result);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			log.error("新增复工人员出错!");
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 根据ID修改复工人员信息
	 * @param dict
	 * @return
	 */
	@ApiOperation(value = "根据ID修改复工人员信息", httpMethod = "PUT", notes = "根据ID修改复工人员信息")
	@RequestMapping(value = "/updateReturnToWorkUser", method = RequestMethod.PUT)
	public ResponseMessage<Map<String, String>> updateDictInfo(@RequestBody ReturnToWorkUser returnToWorkUser) {
		ResponseMessage<Map<String, String>> rm = new ResponseMessage<Map<String, String>>();
		try {
			int result = service.save(returnToWorkUser);
			log.info("更新{}条复工人员", result);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			log.error("更新复工人员出错!");
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 根据ID删除复工人员
	 * @param ids
	 * @return
	 */
	@ApiOperation(value = "删除复工人员", httpMethod = "DELETE", notes = "删除复工人员")
	@RequestMapping(value = "/delReturnToWorkUser", method = RequestMethod.DELETE)
	public ResponseMessage<ReturnToWorkUser> delDictInfoById(@RequestParam(required = true) String ids) {
		ResponseMessage<ReturnToWorkUser> rm = new ResponseMessage<ReturnToWorkUser>();
		try {
			if (StringUtils.isBlank(ids)) {
				rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, "参数不能为空");
				return rm;
			}
			String[] idString = ids.split(",");
			for (String id : idString) {
				service.delete(Integer.parseInt(id));
			}
			log.info("删除{}条复工人员", idString.length);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			log.error("删除复工人员出错!");
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 根据类别获取复工人员列表
	 * @param ReturnToWorkUser
	 * @return
	 */
	@ApiOperation(value = "根据类别获取复工人员列表", httpMethod = "GET", notes = "根据类别获取复工人员列表")
	@RequestMapping(value = "/findReturnToWorkUserList", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<Object> findReturnToWorkUserList(@RequestParam(required = false) Integer page,
			@RequestParam(required = false) Integer rows, @RequestParam(required = false) String userName,
			@RequestParam(required = false) String mobile, @RequestParam(required = false) String workFlag,
			@RequestParam(required = false) String projectId) {
		ResponseMessage<Object> rm = new ResponseMessage<Object>();
		try {
			/*String projectId = request.getHeader("projectId");
			if (StringUtils.isBlank(projectId)) {
				rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.R_PARAM_ERROR.msg);
				return rm;
			}*/
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userName", userName);
			params.put("mobile", mobile);
			params.put("workFlag", workFlag);
			params.put("page", page);
			params.put("rows", rows);
			params.put("projectId", projectId);
			//List<ReturnToWorkUser> list = service.findList(params);
			PageBean<ReturnToWorkUser> data = service.findListPage(params);
			PageBean<ReturnToWorkUser> pageInfo = new PageBean<ReturnToWorkUser>();
			pageInfo.setPages(data.getPages());
			pageInfo.setCurrPage(data.getCurrPage());
			pageInfo.setTotalCount(data.getTotalCount());
			pageInfo.setPageSize(data.getPageSize());
			pageInfo.setTotalPageCount(data.getTotalPageCount());
			rm.setData(pageInfo);
			log.info("查询到{}条复工人员信息", data.getPages().size());
			rm.setData(pageInfo);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			log.error("查询复工人员信息出错！");
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 导入学员清单
	 * @param file
	 * @param clientid
	 * @return
	 * @throws IOException
	 */
	/*@ApiOperation(notes = "excel复工人员信息文件上传", value = "excel复工人员信息文件上传")
	@RequestMapping(value = "/ftpUpload", method = RequestMethod.POST)
	@ResponseBody
	public Object ftpUpload(MultipartFile file)*/
	@ApiOperation(value = "根据类别获取复工人员列表", httpMethod = "POST", notes = "根据类别获取复工人员列表")
	@RequestMapping(value = "/addReturnToWorkUser", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage<Object> addReturnToWorkUser(@RequestParam MultipartFile file, HttpServletRequest request)
			throws IOException {
		ResponseMessage<Object> rm = new ResponseMessage<Object>();

		List<ReturnToWorkUser> list = new ArrayList<ReturnToWorkUser>();
		XSSFWorkbook workbook = null;
		try {
			String fileName = file.getOriginalFilename();
			InputStream in = file.getInputStream();
			String fileType = fileName.substring(fileName.lastIndexOf("."));
			if (".xlsx".equals(fileType)) {
				workbook = new XSSFWorkbook(in); // 2007+
			} else {
				rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "解析的文件格式有误！");
				return rm;
			}

			//获取第一个工作表
			XSSFSheet sheet = workbook.getSheet("t_return_to_work_user");

			//获取sheet中第一行行号
			int firstRowNum = sheet.getFirstRowNum();
			//获取sheet中最后一行行号
			int lastRowNum = sheet.getLastRowNum();

			//循环插入数据
			for (int i = firstRowNum + 1; i <= lastRowNum; i++) {
				XSSFRow row = sheet.getRow(i);
				if (null == row) {
					continue;
				}
				ReturnToWorkUser returnToWorkUser = new ReturnToWorkUser();

				XSSFCell username = row.getCell(0);//学员名称
				if (username != null) {
					username.setCellType(Cell.CELL_TYPE_STRING);
					returnToWorkUser.setUserName((username.getStringCellValue()));
				} else {
					continue;
				}

				XSSFCell phone = row.getCell(1);//联系方式
				if (phone != null) {
					phone.setCellType(Cell.CELL_TYPE_STRING);
					if (StringUtils.isBlank(phone.getStringCellValue())) {
						continue;
					}
					returnToWorkUser.setMobile((phone.getStringCellValue()));
				} else {
					continue;
				}

				XSSFCell roleCode = row.getCell(2);//职位
				if (roleCode != null) {
					roleCode.setCellType(Cell.CELL_TYPE_STRING);
					returnToWorkUser.setRoleCode((roleCode.getStringCellValue()));
				}

				XSSFCell companyName = row.getCell(3);//公司名称
				if (companyName != null) {
					companyName.setCellType(Cell.CELL_TYPE_STRING);
					returnToWorkUser.setCompanyName((companyName.getStringCellValue()));

				}

				XSSFCell buildingLocation = row.getCell(4);//地址
				if (buildingLocation != null) {
					buildingLocation.setCellType(Cell.CELL_TYPE_STRING);
					returnToWorkUser.setBuildingLocation((buildingLocation.getStringCellValue()));
					String location = buildingLocation.getStringCellValue();
					if (location.indexOf("B座") > -1) {
						returnToWorkUser.setProjectId(PropertyUtil.getProperty("huarun_b_project_id"));
					} else if (location.indexOf("C座") > -1) {
						returnToWorkUser.setProjectId(PropertyUtil.getProperty("huarun_c_project_id"));
					} else if (location.indexOf("D座") > -1) {
						returnToWorkUser.setProjectId(PropertyUtil.getProperty("huarun_d_project_id"));
					} else if (location.indexOf("E座") > -1) {
						returnToWorkUser.setProjectId(PropertyUtil.getProperty("huarun_e_project_id"));
					} else if (location.indexOf("中国华润大厦") > -1) {
						returnToWorkUser.setProjectId(PropertyUtil.getProperty("chunsun_project_id"));
						String floor = "";
						if (location.indexOf("楼") > -1) {
							floor = location.substring(location.indexOf("中国华润大厦") + 6, location.indexOf("楼"));
						} else if (location.indexOf("层") > -1) {
							floor = location.substring(location.indexOf("中国华润大厦") + 6, location.indexOf("层"));
						} else if (location.indexOf("F") > -1) {
							floor = location.substring(location.indexOf("中国华润大厦") + 6, location.indexOf("F"));
						}
						if (StringUtils.isNotBlank(floor) && NumberUtils.isNumber(floor)) {
							returnToWorkUser.setCreateBy(floor);
						}
					}
				}

				XSSFCell workFlag = row.getCell(5);//复工状态
				if (workFlag != null) {
					workFlag.setCellType(Cell.CELL_TYPE_STRING);
					if ("复工".equals(workFlag.getStringCellValue())) {
						returnToWorkUser.setWorkFlag("1");
					} else {
						returnToWorkUser.setWorkFlag("0");
					}
				}

				returnToWorkUser.setCreateDate(new Date());
				list.add(returnToWorkUser);
			}
			List<ReturnToWorkUser> resultList = new ArrayList<ReturnToWorkUser>();
			for (ReturnToWorkUser rtwu : list) {
				if (StringUtils.isBlank(rtwu.getProjectId())) {
					rtwu.setRemarks("地址异常");
					resultList.add(rtwu);
					continue;
				}
				if (rtwu.getMobile().matches(REGEX_MOBILE)) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("projectId", rtwu.getProjectId());
					map.put("mobile", rtwu.getMobile());
					ReturnToWorkUser reToWork = service.getBeanByParams(map);
					if (null == reToWork) {
						service.save(rtwu);
					} else {
						rtwu.setRemarks("数据重复");
						resultList.add(rtwu);
					}
				} else {
					rtwu.setRemarks("手机号异常");
					resultList.add(rtwu);
				}
			}
			System.out.println("excel导入" + (list.size() - resultList.size()) + "条数据");
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("failList", resultList);
			dataMap.put("succCount", (list.size() - resultList.size()));
			rm.setData(dataMap);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			log.error("excel导入复工人员信息异常！");
			e.printStackTrace();
		} finally {

		}
		return rm;
	}

	private static String getBcdApiHost(String projectId) {
		if (projectId.equals(PropertyUtil.getProperty("huarun_b_project_id")))
			return PropertyUtil.getProperty("visitor_b_url");
		if (projectId.equals(PropertyUtil.getProperty("huarun_c_project_id")))
			return PropertyUtil.getProperty("visitor_c_url");
		if (projectId.equals(PropertyUtil.getProperty("huarun_d_project_id"))) {
			return PropertyUtil.getProperty("visitor_d_url");
		}
		return PropertyUtil.getProperty("visitor_bcd_url");
	}

	public static String replaceLanToWan(String lanUrl, String wanHost) {
		String pattern = "http://\\d*\\.\\d*\\.\\d*\\.\\d*:\\d*";
		Pattern r = Pattern.compile(pattern);
		Matcher m = r.matcher(lanUrl);
		if (m.find()) {
			String host = m.group(0);
			return lanUrl.replace(host, wanHost);
		}
		return lanUrl;
	}

	/**
	 * yyyy-MM-dd HH:mm 传入日期
	 *
	 * @param date
	 * @return
	 */
	public static String getReqHourDate(Date date) {
		return LONG_HOUR_FORMAT.format(date);
	}

	public static void main(String[] args) {
		System.out.println(NumberUtils.isNumber("-123"));
		System.out.println(NumberUtils.isNumber("1.23"));
	}
}
